package com.or.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.or.app.StateApplication;
import com.or.log.LogWirter;
import com.or.utils.C;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * Created by O_R on 2016/2/28.
 */
public class TrailSaveService extends Service{

    private boolean gps_available = false;
    private StateApplication sapp;
    private LogWirter logWirter;
    private LocationManager mlocationmgr;
    private ArrayList<GpsSatellite> numSatelliteList = new ArrayList<GpsSatellite>(); // 卫星信号
    private String gpsinfo = "";
    private String locationinfo = "";


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        sapp = (StateApplication) getApplication();
        sapp.setState(true);
        sendBroadcast(new Intent(C.BDR_ACTION_STATE));

        mlocationmgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (mlocationmgr.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            sendlog("服务已启动, 开始记录gps轨迹.");
            sendlog("gps模块正常.");
            sendlog("开始搜索卫星...");
            mlocationmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, intent.getIntExtra("t", 3000), 1, locationListener);
            mlocationmgr.addGpsStatusListener(gpsStatusListener);

            try{
                logWirter = new LogWirter(this);
               // logWirter.log("what the fuck?");
            }catch (Exception e){
                sendlog("启动失败:" + e.getMessage());
                stopSelf();/*把自己停掉咯, 启动失败了.*/
            }
        }else{
            sendlog("请先开启gps模块.");
            stopSelf();
        }
        return super.onStartCommand(intent, flags, startId);
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        sapp.setState(false);
        if(logWirter != null) logWirter.exit();
        if(mlocationmgr != null){
            mlocationmgr.removeGpsStatusListener(gpsStatusListener);
            mlocationmgr.removeUpdates(locationListener);
        }
        sendlog("服务已停止, 停止记录gps轨迹.");
        sendBroadcast(new Intent(C.BDR_ACTION_STATE));
    }

    private void sendlog(String str){
        Intent intent = new Intent(C.BDR_ACTION_LOG);
        intent.putExtra("log", str);
        intent.putExtra("type", 1);
        sendBroadcast(intent);
    }

    private void sendInfo(){
        Intent intent = new Intent(C.BDR_ACTION_LOG);
        intent.putExtra("gpsinfo", gpsinfo + "\n" + locationinfo);
        intent.putExtra("type", 2);
        sendBroadcast(intent);
    }


    private void sendGpsStatus(){
        Intent intent = new Intent(C.BDR_ACTION_LOG);
        intent.putExtra("gpsinfo", gps_available);
        intent.putExtra("type", 3);
        sendBroadcast(intent);
    }

    private void sendSaveCount(){
        Intent intent = new Intent(C.BDR_ACTION_LOG);
        intent.putExtra("savecount", sapp.getNowsavepontcount());
        intent.putExtra("type", 4);
        sendBroadcast(intent);
    }

    private GpsStatus.Listener gpsStatusListener = new GpsStatus.Listener(){

        @Override
        public void onGpsStatusChanged(int event) {
            GpsStatus status = mlocationmgr.getGpsStatus(null);
            updateGpsMsg(event, status);
            sendInfo();
        }
    };

    private LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            updateLocationMsg(location);
            sendInfo();
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {/*这个方法不靠谱*/
          /*  switch (status){
                case LocationProvider.AVAILABLE:
                    gps_available = true;
                    sendlog("gps信号正常, 开始记录.");
                    break;
                case LocationProvider.OUT_OF_SERVICE:
                    gps_available = false;
                    sendlog("gps不可用, 停止记录.");
                    break;
                case LocationProvider.TEMPORARILY_UNAVAILABLE:
                    gps_available = false;
                    sendlog("gps不可用, 停止记录.");
                    break;
            }
            sendGpsStatus();*/
        }

        @Override
        public void onProviderEnabled(String provider) {}

        @Override
        public void onProviderDisabled(String provider) {
            sendlog("gps 被关闭了.");
            stopSelf();
        }
    };

    private void updateLocationMsg(Location loc) {/*解析状态信息 没有则返回空*/
        StringBuilder sb = new StringBuilder();
        if (loc != null) {
            double lat = loc.getLatitude();
            double lng = loc.getLongitude();
            sb.append("纬度：" + lat + "  经度：" + lng);
            if(gps_available && logWirter != null){
                logWirter.log(lat + "," + lng);
                sapp.add();
                sendSaveCount();
            }
            if (loc.hasAccuracy()) {
                sb.append("\n精度：" + loc.getAccuracy());
                if(loc.getAccuracy() < 50){
                    gps_available = true;
                }else{
                    gps_available = false;
                }
                sendGpsStatus();
            }
            if (loc.hasAltitude()) {
                sb.append("   海拔：" + loc.getAltitude() + "m");
            }
            if (loc.hasBearing()) {// 偏离正北方向的角度
                sb.append("\n方向：" + loc.getBearing());
            }
            if (loc.hasSpeed()) {
                if (loc.getSpeed() * 3.6 < 5) {
                    sb.append("   速度：0.0km/h");
                } else {
                    sb.append("   速度：" + loc.getSpeed() * 3.6 + "km/h");
                }
            }
        }
        locationinfo = sb.toString();
    }

    private void updateGpsMsg(int event, GpsStatus status){
        StringBuilder sb2 = new StringBuilder("");
        if (status == null) {
            sb2.append("当前卫星数：" + 0);
        } else if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
            int maxSatellites = status.getMaxSatellites();
            Iterator<GpsSatellite> it = status.getSatellites().iterator();
            numSatelliteList.clear();
            int count = 0;
            int mValid = 0;
            StringBuilder snrs = new StringBuilder();
            while (it.hasNext() && count <= maxSatellites) {
                GpsSatellite s = it.next();
                numSatelliteList.add(s);
                snrs.append(s.getSnr());
                snrs.append(",");
            //    if(s.getSnr()) mValid++;
                count++;
            }
            Intent intent = new Intent(C.BDR_ACTION_LOG);
            intent.putExtra("gpssnr", snrs.toString());
            intent.putExtra("type", 5);
            sendBroadcast(intent);
            sb2.append("当前卫星数：" + numSatelliteList.size());
            sb2.append("/" + 0);
        }
        gpsinfo = sb2.toString();
    }
}
